package com.yangjun.controller.usermanage;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yangjun.dao.impl.usermanage.ExcelRoleManagerDaoImpl;
import com.yangjun.dao.mybatis.mapper.usermanage.ExcelRoleManagerMapper;
import com.yangjun.entity.report.DvExcelFieldDefinitionEntity;
import com.yangjun.entity.usermanage.ExcelReportDimEntity;
import com.yangjun.entity.usermanage.ExcelReportEntity;
import com.yangjun.entity.usermanage.ExcelRoleEntity;
import com.yangjun.entity.usermanage.ExcelRoleReportEntity;
import com.yangjun.entity.usermanage.ExcelUserRoleEntity;
import com.yangjun.entity.usermanage.UsersEntity;
import com.yangjun.service.common.CommonService;
import com.yangjun.utils.AjaxJson;

@Controller
@RequestMapping("/excelrole")
public class ExcelRoleManagerController {
	
	@Autowired
	private ExcelRoleManagerMapper mapper;
	
	@Autowired
	ExcelRoleManagerDaoImpl dao;
	
	
	@Autowired
	private CommonService commonService;
	
	
	
	/**
	 * http://192.168.7.32:8080/excelrole/getAllRoles?type=rolename&search=超级管理员
	 * 获取所有角色信息
	 * @param response
	 * @param type rolename/prolename
	 * @param search
	 * @return
	 */
	 @RequestMapping("/getAllRoles")
	 @ResponseBody
	 public AjaxJson getAllRoles(HttpServletResponse response,
			 @RequestParam(value = "type",required = true)String type,
			 @RequestParam(value = "search",required = true)String search){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 Map<String, Object> paremeter = Maps.newHashMap();
		 paremeter.put("type", type);
		 paremeter.put("search", search);
		 List<ExcelRoleEntity> currentExcelRoleInfo = mapper.getCurrentExcelRoleInfo(paremeter);
		 Map<String, Object> attributes = Maps.newHashMap();
		 attributes.put("currentExcelRoleInfo", currentExcelRoleInfo);
		 j.setAttributes(attributes);
		 return j;
	 }
	 
	 
	 /**
	  * 
	  * http://192.168.7.32:8080/excelrole/getNormalRoleInfo
	  * 角色管理  添加角色 授权人列表
	  * @param response
	  * @return
	  */
	 @RequestMapping("/getNormalRoleInfo")
	 @ResponseBody
	 public AjaxJson getNormalRoleInfo(HttpServletResponse response){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 List<ExcelRoleEntity> normaRoleInfo = mapper.getExcelNormalRoleInfo();
		 Map<String, Object> attributes = Maps.newHashMap();
		 attributes.put("normaRoleInfo", normaRoleInfo);
		 j.setAttributes(attributes);
		 return j;
	 }
	 
	 
	 /**
	  * 
	  * http://192.168.7.32:8080/excelrole/addRole?rolename=渠道总监&pid=1
	  * 添加角色
	  * @param response
	  * @param rolename
	  * @param pid
	  * @return
	  */
	 @RequestMapping("/addRole")
	 @ResponseBody
	 public AjaxJson addRole(HttpServletResponse response,
			 @RequestParam(value = "rolename",required = true)String rolename,
			 @RequestParam(value = "pid",required = true)String pid){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 boolean ok = dao.addRole(rolename, Integer.parseInt(pid));
		 if(!ok){
			 j.setSuccess(false);
			 j.setMsg("角色已存在||操作失败");
			 return j;
		 }
		 return j;
	 }
	 
	 /**
	  * http://192.168.7.32:8080/excelrole/updateRole?rolename=渠道总监&pid=1&id=2
	  * 修改角色
	  * @param response
	  * @param rolename
	  * @param pid
	  * @param id
	  * @return
	  */
	 @RequestMapping("/updateRole")
	 @ResponseBody
	 public AjaxJson updateRole(HttpServletResponse response,
			 @RequestParam(value = "rolename",required = true)String rolename,
			 @RequestParam(value = "pid",required = true)String pid,
			 @RequestParam(value = "id",required = true)String id){
		 
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 boolean ok = dao.updateRole(rolename, Integer.parseInt(pid), Integer.parseInt(id));
		 if(!ok){
			 j.setSuccess(false);
			 j.setMsg("操作失败");
			 return j;
		 }
		 return j;
	 }
	 
	 /**
	  * http://192.168.7.32:8080/excelrole/updateRoleStatu?status=0&id=1
	  * 修改角色状态
	  * @param response
	  * @param status
	  * @param id
	  * @return
	  */
	 @RequestMapping("/updateRoleStatu")
	 @ResponseBody
	 public AjaxJson updateRoleStatu(HttpServletResponse response,
			 @RequestParam(value = "status",required = true)String status,
			 @RequestParam(value = "id",required = true)String id){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 boolean ok = dao.updateRoleStatus(Integer.parseInt(status), Integer.parseInt(id));
		 if(!ok){
			 j.setSuccess(false);
			 j.setMsg("操作失败");
			 return j;
		 }
		 return j;
	 }
	 
	 
	 
	 /**
	  * http://192.168.7.32:8080/excelrole/getExcelReport
	  * @param response
	  * @return
	  */
	 @RequestMapping("/getExcelReport")
	 @ResponseBody
	 public AjaxJson getExcelReport(HttpServletResponse response){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 List<ExcelReportEntity> allExcelReportInfo = mapper.getAllExcelReportInfo();
		 Map<String, Object> attributes = Maps.newHashMap();
		 attributes.put("allExcelReportInfo", allExcelReportInfo);
		 j.setAttributes(attributes);
		 return j;
	 }
	 
	 
	 
	 /**
	  * 
	  * 角色下所有报表信息
	  * http://192.168.7.32:8080/excelrole/getRoleReport?roleid=1
	  * @param response
	  * @param id
	  * @return
	  */
	 @RequestMapping("/getRoleReport")
	 @ResponseBody
	 public AjaxJson getRoleReport(HttpServletResponse response,
		 @RequestParam(value = "roleid",required = true)String roleid){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 List<ExcelRoleReportEntity> roleReportInfo = mapper.getRoleReportInfo(Integer.valueOf(roleid));
		 Map<String, Object> attributes = Maps.newHashMap();
		 attributes.put("roleReportInfo", roleReportInfo);
		 j.setAttributes(attributes);
		 return j;
	 }
	 
	 
	 /** http://192.168.7.32:8080/excelrole/addRoleReport?roleid=&excelid=&field=&type=&dim=
	  *  角色分配报表
	  * @param response
	  * @param roleid
	  * @param excelid
	  * @param field
	  * @param type
	  * @return
	  */
	 @RequestMapping("/addRoleReport")
	 @ResponseBody
	 public AjaxJson addRoleReport(HttpServletResponse response,
			 @RequestParam(value = "roleid",required = true)String roleid,
			 @RequestParam(value = "excelid",required = true)String excelid,
			 @RequestParam(value = "field",required = true)String field,
			 @RequestParam(value = "type",required = true)String type,
			 @RequestParam(value = "dim",required = true)String dim
			 ){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 boolean ok = dao.addRoleReport( Integer.parseInt(roleid),excelid,field, Integer.parseInt(type),dim);
		 if(!ok){
			 j.setSuccess(false);
			 j.setMsg("该角色已添加该报表 || 操作失败");
			 return j;
		 }
		 return j;
	 }
	 
	 
	 /**
	  * http://192.168.7.32:8080/excelrole/updateRoleReport?id=&field=&type=&dim=
	  * 修改角色报表
	  * @param response
	  * @param roleid
	  * @param excelid
	  * @param field
	  * @param type
	  * @return
	  */
	 @RequestMapping("/updateRoleReport")
	 @ResponseBody
	 public AjaxJson updateRoleReport(HttpServletResponse response,
			 @RequestParam(value = "id",required = true)String id,
			 @RequestParam(value = "field",required = true)String field,
			 @RequestParam(value = "type",required = true)String type,
			 @RequestParam(value = "dim",required = true)String dim
			 ){
		 
//		 System.err.println("xxxx="+field);
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 boolean ok = dao.updateRoleReport(Integer.parseInt(id),field, Integer.parseInt(type),dim);
		 if(!ok){
			 j.setSuccess(false);
			 j.setMsg("操作失败");
			 return j;
		 }
		 return j;
	 }
	 
	 /**
	  * 
	  * http://192.168.7.32:8080/excelrole/updateRoleReportStatu?status=&id=
	  * 修改角色报表状态
	  * @param response
	  * @param status
	  * @param id
	  * @return
	  */
	 @RequestMapping("/updateRoleReportStatu")
	 @ResponseBody
	 public AjaxJson updateRoleReportStatu(HttpServletResponse response,
			 @RequestParam(value = "status",required = true)String status,
			 @RequestParam(value = "id",required = true)String id){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 boolean ok = dao.updateRoleReportStatu(Integer.parseInt(status), Integer.parseInt(id));
		 if(!ok){
			 j.setSuccess(false);
			 j.setMsg("操作失败");
			 return j;
		 }
		 return j;
	 }
	 
	 
	 /**
	  * http://192.168.7.32:8080/excelrole/getExcelDeminsion?excelId=singleProduct&roleid=1&type=update
	  * @param response
	  * @param excelId
	  * @return
	  */
	 @RequestMapping("/getExcelDeminsion")
	 @ResponseBody
	 public AjaxJson getExcelDeminsion(HttpServletResponse response,
		 @RequestParam(value = "excelId",required = true)String excelId,
		 @RequestParam(value = "roleid",required = true)String roleid,
		 @RequestParam(value = "type",required = true)String type){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 Map<String, Object> attributes = Maps.newHashMap();
		 List<DvExcelFieldDefinitionEntity> excelFieldDefinitionList = mapper.queryField(excelId);
			Map<String,List<Map<String,Object>>> targetMap = Maps.newHashMap();
			List<Map<String,Object>> targetList =null;
			for(DvExcelFieldDefinitionEntity excelFieldDefinitionEntity : excelFieldDefinitionList){
				String categoryId = excelFieldDefinitionEntity.getCategoryId();
				if(StringUtils.isNotBlank(categoryId)){
					String entityName = excelFieldDefinitionEntity.getEntityName();
					String title = excelFieldDefinitionEntity.getTitle();
					int sort = excelFieldDefinitionEntity.getFieldSort();
					Map<String,Object> itemMap = Maps.newHashMap();
					itemMap.put("value", entityName);
					itemMap.put("name", title);
					itemMap.put("sort", sort);
					targetList = targetMap.get(categoryId);
					if(targetList!=null){
						targetList.add(itemMap);
					}else{
						targetList = Lists.newArrayList();
						targetList.add(itemMap);
						targetMap.put(categoryId, targetList);
					}
				}
			}
			
		 List<List<Map<String,Object>>>	 fieldList = new ArrayList<List<Map<String,Object>>>();
		 List<DvExcelFieldDefinitionEntity> categoryList = mapper.queryCategory(excelId);	
		 for(DvExcelFieldDefinitionEntity entity:categoryList){
			 fieldList.add(targetMap.get(entity.getCategoryId()));
		 }
		 
		 List<String> roleExistField = null;
		 List<String> roleExistDim = new ArrayList<String>();
		 Integer roleExistType = null;
		 if("update".equals(type)){
			 ExcelRoleReportEntity entity = mapper.roleExistField(Integer.valueOf(roleid),excelId);
			 if(entity!=null){
				 roleExistField =  Arrays.asList(entity.getField().replace("|", ",").split(","));
				 roleExistType = entity.getType();
				 String dim = entity.getDim();
				 if(StringUtils.isNotBlank(dim)){
					 roleExistDim = Arrays.asList(dim.replace("|", ",").split(","));
				 }
			 }
		 }
		 
		 
		 
		 Map<String, Object> dim = new HashMap<String, Object>();
		 List<String> dimK = new ArrayList<String>();
		 List<List<String>> dimV = new ArrayList<List<String>>();
		 
		 /**
		  * 单品分析,活动套餐,订单交易特殊添加平台
		  */
		 if(excelId.equals("singleProduct") 
				 || excelId.equals("activePackage") 
				 || excelId.equals("orderTransaction")
				 || excelId.equals("commodityFlow")){
			 dimK.add("平台");
			 List<String> platformList = new ArrayList<String>();
			 List<Map<String, Object>> platformListByMap = commonService.getPlatformList();
			 for (Map<String, Object> map : platformListByMap) {
				 String sourcename = map.get("sourcename").toString();
				 platformList.add(sourcename);
			}
			 dimV.add( platformList);
			 
		 }
		 
		 
		 List<ExcelReportDimEntity> dimList = mapper.queryDim(excelId);
		 for (ExcelReportDimEntity entity : dimList) {
			 dimK.add(entity.getDim());
			 dimV.add(Arrays.asList(entity.getValue().split(",")));
		}
		 
		 
		 dim.put("dimK", dimK);
		 dim.put("dimV", dimV);
		 
		 
		 attributes.put("dim", dim);
		 attributes.put("category", categoryList);
		 attributes.put("existType", roleExistType);
		 attributes.put("existField", roleExistField);
		 attributes.put("existDim", roleExistDim);
		 attributes.put("excelField", fieldList);
		 j.setAttributes(attributes);
		 return j;
	 } 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 /**
	  * 
	  * **********************************角色分配***************************************************
	  * 
	  */
	 
	 
	 

 
	/**
	 * 获取所有用户角色信息
	 * http://192.168.7.32:8080/excelrole/getAllUserRoles?type=rolename&search=超级管理员&username=zmn
	 * @param response
	 * @param type realname/username/rolename/auth_realname
	 * @param search
	 * @return
	 */
	 @RequestMapping("/getAllUserRoles")
	 @ResponseBody
	 public AjaxJson getAllUserRoles(HttpServletResponse response,
			 @RequestParam(value = "type",required = true)String type,
			 @RequestParam(value = "search",required = true)String search,
			 @RequestParam(value = "username",required = true)String username){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 Map<String, Object> paremeter = Maps.newHashMap();
		 paremeter.put("type", type);
		 paremeter.put("search", search);
		 paremeter.put("username", username);
		 paremeter.put("roleid", null);
		 
		 List<Integer> userRoleIdList = mapper.getUserRoleId(username);
		 if(userRoleIdList.contains(new Integer(1))){
//			 System.out.println("超级管理员");
			 paremeter.put("roleid", 1);
		 }
		 List<ExcelUserRoleEntity> allUserRoleInfo = mapper.getAllUserRoleInfo(paremeter);
		 Map<String, Object> attributes = Maps.newHashMap();
		 attributes.put("allUserRoleInfo", allUserRoleInfo);
		 j.setAttributes(attributes);
		 return j;
	 }
	 
	 
	 /**
	  * 
	  * http://192.168.7.32:8080/excelrole/addUserRole?username=&realname=&roleid=&auth_username=
	  * 给用户添加角色
	  * @param response
	  * @param username
	  * @param realname
	  * @param roleid
	  * @param auth_username
	  * @return
	  */
	 @RequestMapping("/addUserRole")
	 @ResponseBody
	 public AjaxJson addUserRole(HttpServletResponse response,
			 @RequestParam(value = "username",required = true)String username,
			 @RequestParam(value = "realname",required = true)String realname,
			 @RequestParam(value = "roleid",required = true)String roleid,
			 @RequestParam(value = "auth_username",required = true)String auth_username){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 UsersEntity curUserEntity = mapper.getUseridAndRealnameOfUsername(username);
		 if(curUserEntity==null){
			 j.setSuccess(false);
			 j.setMsg("该用户不存在,请联系管理员添加");
			 return j;
		 }
		 UsersEntity authEntity = mapper.getUseridAndRealnameOfUsername(auth_username);
		 
		 
		 boolean ok = dao.addUserRole(curUserEntity.getUserid(),username,realname, Integer.parseInt(roleid),auth_username,authEntity.getRealname());
		 if(!ok){
			 j.setSuccess(false);
			 j.setMsg("该用户已被授权||操作失败");
			 return j;
		 }
		 return j;
	 }
	 
	 
	 /**
	  * 
	  * http://192.168.7.32:8080/excelrole/updateUserRole?realname=&roleid=&auth_username=&id=
	  * 修改用户角色
	  * @param response
	  * @param username
	  * @param realname
	  * @param roleid
	  * @param auth_username
	  * @param id
	  * @return
	  */
	 @RequestMapping("/updateUserRole")
	 @ResponseBody
	 public AjaxJson updateUserRole(HttpServletResponse response,
			 @RequestParam(value = "realname",required = true)String realname,
			 @RequestParam(value = "roleid",required = true)String roleid,
			 @RequestParam(value = "auth_username",required = true)String auth_username,
			 @RequestParam(value = "id",required = true)String id
			 ){
		 
		 System.out.println(realname+"\t"+roleid+"\t"+auth_username+"\t"+id);
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 UsersEntity authEntity = mapper.getUseridAndRealnameOfUsername(auth_username);
		 boolean ok = dao.updateUserRole(realname, Integer.parseInt(roleid),auth_username,authEntity.getRealname(),Integer.parseInt(id));
		 if(!ok){
			 j.setSuccess(false);
			 j.setMsg("操作失败");
			 return j;
		 }
		 return j;
	 }
	 
	 
	 
	 /**
	  * 
	  * http://192.168.7.32:8080/excelrole/updateUserRoleStatu?status=&id=
	  * 修改用户角色状态
	  * @param response
	  * @param status
	  * @param id
	  * @return
	  */
	 @RequestMapping("/updateUserRoleStatu")
	 @ResponseBody
	 public AjaxJson updateUserRoleStatu(HttpServletResponse response,
			 @RequestParam(value = "status",required = true)String status,
			 @RequestParam(value = "id",required = true)String id){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 boolean ok = dao.updateUserRoleStatu(Integer.parseInt(status), Integer.parseInt(id));
		 if(!ok){
			 j.setSuccess(false);
			 j.setMsg("操作失败");
			 return j;
		 }
		 return j;
	 }
	 
	 
	 
	 /**
	  * 
	  * http://192.168.7.32:8080/excelrole/getNormalSonRoleInfo?username=
	  * 角色分配 新增用户角色 角色列表
	  * @param response
	  * @return
	  */
	 @RequestMapping("/getNormalSonRoleInfo")
	 @ResponseBody
	 public AjaxJson getNormalSonRoleInfo(HttpServletResponse response,
		 @RequestParam(value = "username",required = true)String username){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("text/html;charset=UTF-8");
		 AjaxJson j = new AjaxJson();
		 
		 List<ExcelRoleEntity> normaSonRoleInfo =null;
		 
		 List<Integer> userRoleIdList = mapper.getUserRoleId(username);
		 if(userRoleIdList.contains(new Integer(1))){
			 System.out.println("超级管理员");
			 normaSonRoleInfo = mapper.getExcelNormalRoleInfo();
		 }else{
			 normaSonRoleInfo = mapper.getNormalSonRoleInfo(username);
		 }
		 Map<String, Object> attributes = Maps.newHashMap();
		 attributes.put("normaSonRoleInfo", normaSonRoleInfo);
		 j.setAttributes(attributes);
		 return j;
	 }
	 

}
